package cn.itcast.controller;

import cn.itast.domain.Permission;
import cn.itast.domain.Role;
import cn.itcast.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/findAll")
    @RolesAllowed("ROLE_USER")
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView();
        List<Role> roleList = roleService.findAll();

        mv.addObject("roleList", roleList);
        mv.setViewName("role-list");
        return mv;
    }

    @RequestMapping("/findById.do")
    @RolesAllowed("ROLE_ADMIN")
    public ModelAndView findById(@RequestParam(name = "id",required = true)String roleId){

        ModelAndView mv = new ModelAndView();
        Role role = roleService.findById(roleId);

        mv.addObject("role",role);
        mv.setViewName("role-show");

        return mv;
    }

    @RequestMapping("/save")
    public String save(Role role){
        roleService.save(role);
        return "redirect:findAll.do";

    }


    @RequestMapping("/findAndUpdateByRoleId")
    public ModelAndView findAndUpdateByRoleId(@RequestParam(name = "id",required = true)String roleId){
        ModelAndView mv =new ModelAndView();
        Role role=roleService.findById(roleId);
        List<Permission> permissionList = roleService.findOtherPermission(roleId);

        mv.addObject("permissionList",permissionList);
        mv.addObject("role",role);
        mv.setViewName("role-permission-add");
        return mv;

    }

    @RequestMapping("/addPermissionToRole")
    public String addPermissionToRole(@RequestParam(name = "roleId", required = true)String roleId,
                                @RequestParam(name = "permissionId", required = true)String[] permissionId){

        roleService.addPermissionToRole(roleId,permissionId);
        return "redirect:findAll.do";
    }
}